package fang365

import (
	"encoding/json"
	"fmt"
	"github.com/xiaobaiskill/fang/internal/proxypool"
	"github.com/xiaobaiskill/fang/pkg/log"
	"io"
	"io/ioutil"
	"net/http"
)

var (
	fang_url string = `https://esfmapi.house365.com/taofang/v1.0/esf/?method=getHouse&name=HouseSell&cityKey=%s&city=%s&client=tf&version=8.0.90&v=8.0.90&commitId=ed9b136&api_key=android&tt=%d&name=HouseSell&pagesize=%d&infofrom=1&page=1&order=creattime&desc=DESC&guid=`
)

type fangInfo struct {
	city     string // 城市
	pagesize int    // 页数
}

func (f *fangInfo) Execute() {
	var (
		err        error
		resp       *http.Response
		clientMap  proxypool.HTTPClientMap
		httpclient *http.Client
		index      int
		ok         bool
		retryMax   int = 2
	)
	proxypools := proxypool.Newproxypools()
	req, _ := http.NewRequest("GET", fmt.Sprintf(fang_url, f.city, f.city, f.pagesize,f.pagesize), nil)

	for {
		clientMap, index, ok = proxypools.Pop()
		if !ok {
			return
		}
		retryMax = 2 // 重置单个IP重试次数
		//log.Logger.Info("[getfangingo] 使用的代理ip为：" + clientMap.Ip)
		httpclient = clientMap.Client

		for {
			resp, err = httpclient.Do(req)
			checkOk := f.retryPolicy(resp, err)

			if !checkOk {
				go func(i int, cm proxypool.HTTPClientMap) { proxypools.Push(i, cm) }(index, clientMap)
				f.transformSend(resp)
				return
			}

			if err == nil {
				f.drainBody(resp.Body)
			} else {
				//log.Logger.Error(fmt.Sprintf("[getfangingo]  代理IP：%s,请求失败：%v", clientMap.Ip, err))
				go func(i int, cm proxypool.HTTPClientMap) { proxypools.Del(i, cm) }(index, clientMap)
				break
			}

			retryMax--
			// 单个代理ip的使用次数用完了 ，但是还是没有获取到数据，则结束这个ip ,用下一个
			if retryMax <= 0 {
				go func(i int, cm proxypool.HTTPClientMap) { proxypools.Push(i, cm) }(index, clientMap)
				//log.Logger.Info(fmt.Sprintf("[getfangingo]  重复请求还是没有数据：%v", clientMap))
				break
			}
		}
	}
	log.Logger.Error(fmt.Sprintf("[getfangingo] 最后也没有获取到数据 第%d代理池，ok:%v 结果是啥：%v,", index, ok, resp))
	return
}

// 获取到数据后转化并发送
func (f *fangInfo) transformSend(response *http.Response) {
	if response.StatusCode == http.StatusOK {
		body, err := ioutil.ReadAll(response.Body)
		if err != nil {
			//log.Logger.Error("[getfangingo] [transformSend] responese 数据获取失败")
		}
		fangs := make([]FangInfo, f.pagesize)
		err = json.Unmarshal(body, &fangs)
		if err != nil {
			//log.Logger.Error("[getfangingo] [transformSend] json 数据解析失败")
		}
		f.handle(fangs)
	}
	return
}

func (f *fangInfo) handle(fangs []FangInfo){
	for k,_ := range fangs{
		fangs[k].City = f.city
	}
	go func() {FangQueue <- fangs}()
}


func (f *fangInfo) drainBody(body io.ReadCloser) {
	defer body.Close()

	_, err := io.Copy(ioutil.Discard, io.LimitReader(body, 10))
	if err != nil {
		log.Logger.Error("Error reading response body: " + err.Error())
	}
}

func (f *fangInfo) retryPolicy(resp *http.Response, err error) (bool) {
	if err != nil {
		return true
	}

	if resp.StatusCode == 0 || resp.StatusCode >= 500 {
		return true
	}
	return false
}

func NewFangInfo(c string, p int) *fangInfo {
	return &fangInfo{c, p}
}
